package com.snails.mall.elasticsearch.biz.common.dao.impl;

import com.snails.mall.elasticsearch.biz.common.dao.ElasticsearchDao;
import org.apache.commons.io.IOUtils;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * @author gaoxu
 * date: Created on 2021/11/9 上午11:13
 */

@Component
public class ElasticsearchDaoImpl implements ElasticsearchDao {

    private static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchDaoImpl.class);


    @Autowired
    private RestHighLevelClient restClient;

    @Override
    public Boolean indexExistFlag(String indexName) throws IOException {
        GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);
        return restClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
    }

    @Override
    public Boolean createIndex(String indexName, String aliasName, Resource mappingResource) throws IOException {
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
        // 索引别名不为空,添加索引别名
        if (StringUtils.hasLength(aliasName)) {
            createIndexRequest.alias(new Alias(aliasName));
        }
        // 索引mapping
        String indexMappingJson = IOUtils.toString(mappingResource.getInputStream());
        createIndexRequest.mapping(indexMappingJson, XContentType.JSON);

        CreateIndexResponse createIndexResponse = restClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        LOGGER.info("create index:{} alias:{} response:{}", indexName, aliasName, createIndexResponse.isAcknowledged());
        return createIndexResponse.isAcknowledged();
    }
}
